/*
 * runnable.h
 *
 *  Created on: 2008-9-12
 *      Author: fanliangliang
 */

#ifndef RUNNABLE_H_
#define RUNNABLE_H_

#include "config.h"

BEGIN_NAMESPACE_TOXIC

struct Runnable {
	virtual ~Runnable() {}
	virtual void run() = 0;
};

namespace detail {

	template <class T>
	class RunnableFunctor : public Runnable {
	public:
		RunnableFunctor(const T& f) :_func(f) {}
		virtual void run() { _func(); }
	private:
		T _func;
	};

	// base template for no argument functor
	template <class T>
	struct TransformImplement {
		static Runnable* transform(const T& t) {
			return new RunnableFunctor<T>(t);
		}
	};

	// partial specialization for T*
	template <class T>
	struct TransformImplement<T*> {
		static Runnable* transform(T* t) {
			return t;
		}
	};

	// partial specialization for no argument function
	template <class T>
	struct TransformImplement<T (*)()> {
		static Runnable* transform(T (*t)()) {
			return new RunnableFunctor<T (*)()>(t);
		}
	};

	template <class T>
	inline Runnable* transform(const T& t) {
		return TransformImplement<T>::transform(t);
	}

} // namespace detail

END_NAMESPACE_TOXIC

#endif /* RUNNABLE_H_ */
